package com.jsits.v2x.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 日期工具类
 */
public abstract class DateUtils
{
    /*
     * 日志
     */
    private static final Log logger = LogFactory.getLog(DateUtils.class);
    
    /*
     * 时间年偏移
     */
    public static Date adjustYear(Date date, int offset)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, offset);
        Date newDate = calendar.getTime();
        return newDate;
    }
    
    /*
     * 时间年偏移
     */
    public static String adjustYear(String time, int offset)
    {
        return adjustYear(time, offset, "yyyyMMddHHmmss");
    }
    
    /*
     * 时间年偏移
     */
    public static String adjustYear(String time, int offset, String format)
    {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String retTime = null;
       
        try
        {
            Date date = formatter.parse(time);
            Date newDate = adjustYear(date, offset);
            retTime = formatter.format(newDate);
        }
        catch (ParseException e)
        {
            logger.error("adjustYear fail!" + ExceptionUtils.getStackTrace(e));
        }
        
        return retTime;
    }
    
    /*
     * 时间月偏移
     */
    public static Date adjustMonth(Date date, int offset)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, offset);
        Date newDate = calendar.getTime();
        return newDate;
    }
    
    /*
     * 时间月偏移
     */
    public static String adjustMonth(String time, int offset)
    {
        return adjustMonth(time, offset, "yyyyMMddHHmmss");
    }
    
    /*
     * 时间月偏移
     */
    public static String adjustMonth(String time, int offset, String format)
    {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String retTime = null;
       
        try
        {
            Date date = formatter.parse(time);
            Date newDate = adjustMonth(date, offset);
            retTime = formatter.format(newDate);
        }
        catch (ParseException e)
        {
            logger.error("adjustMonth fail!" + ExceptionUtils.getStackTrace(e));
        }
        
        return retTime;
    }
    
    /*
     * 时间周偏移
     */
    public static Date adjustWeek(Date date, int offset)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 7 * offset);
        Date newDate = calendar.getTime();
        return newDate;
    }
    
    /*
     * 时间周偏移
     */
    public static String adjustWeek(String time, int offset)
    {
        return adjustWeek(time, offset, "yyyyMMddHHmmss");
    }
    
    /*
     * 时间周偏移
     */
    public static String adjustWeek(String time, int offset, String format)
    {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String retTime = null;
       
        try
        {
            Date date = formatter.parse(time);
            Date newDate = adjustWeek(date, offset);
            retTime = formatter.format(newDate);
        }
        catch (ParseException e)
        {
            logger.error("adjustWeek fail!" + ExceptionUtils.getStackTrace(e));
        }
        
        return retTime;
    }
    
    /*
     * 时间日偏移
     */
    public static Date adjustDay(Date date, int offset)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, offset);
        Date newDate = calendar.getTime();
        return newDate;
    }
    
    /*
     * 时间日偏移
     */
    public static String adjustDay(String time, int offset)
    {
        return adjustDay(time, offset, "yyyyMMddHHmmss");
    }
    
    /*
     * 时间日偏移
     */
    public static String adjustDay(String time, int offset, String format)
    {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String retTime = null;

        try
        {
            Date date = formatter.parse(time);
            Date newDate = adjustDay(date, offset);
            retTime = formatter.format(newDate);
        }
        catch (ParseException e)
        {
            logger.error("adjustDay fail!" + ExceptionUtils.getStackTrace(e));
        }
        
        return retTime;
    }
    
    /*
     * 时间小时偏移
     */
    public static Date adjustHour(Date date, int offset)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, offset);
        Date newDate = calendar.getTime();
        
        return newDate;
    }
    
    /*
     * 时间小时偏移
     */
    public static String adjustHour(String time, int offset)
    {
        return adjustHour(time, offset, "yyyyMMddHHmmss");
    }
    
    /*
     * 时间小时偏移
     */
    public static String adjustHour(String time, int offset, String format)
    {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String retTime = null;
       
        try
        {
            Date date = formatter.parse(time);
            Date newDate = adjustHour(date, offset);
            retTime = formatter.format(newDate);
        }
        catch (ParseException e)
        {
            logger.error("adjustHour fail!" + ExceptionUtils.getStackTrace(e));
        }
        
        return retTime;
    }
    
    /*
     * 时间分钟偏移
     */
    public static Date adjustMinute(Date date, int offset)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, offset);
        Date newDate = calendar.getTime();
        return newDate;
    }
    
    /*
     * 时间分钟偏移
     */
    public static String adjustMinute(String time, int offset)
    {
        return adjustMinute(time, offset, "yyyyMMddHHmmss");
    }
    
    /*
     * 时间分钟偏移
     */
    public static String adjustMinute(String time, int offset, String format)
    {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String retTime = null;
       
        try
        {
            Date date = formatter.parse(time);
            Date newDate = adjustMinute(date, offset);
            retTime = formatter.format(newDate);
        }
        catch (ParseException e)
        {
            logger.error("adjustMinute fail!" + ExceptionUtils.getStackTrace(e));
        }
        
        return retTime;
    }
    
    /*
     * 时间秒偏移
     */
    public static Date adjustSecond(Date date, int offset)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, offset);
        Date newDate = calendar.getTime();
        return newDate;
    }
    
    /*
     * 时间秒偏移
     */
    public static String adjustSecond(String time, int offset)
    {
        return adjustSecond(time, offset, "yyyyMMddHHmmss");
    }
    
    /*
     * 时间秒偏移
     */
    public static String adjustSecond(String time, int offset, String format)
    {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String retTime = null;
       
        try
        {
            Date date = formatter.parse(time);
            Date newDate = adjustSecond(date, offset);
            retTime = formatter.format(newDate);
        }
        catch (ParseException e)
        {
            logger.error("adjustSecond fail!" + ExceptionUtils.getStackTrace(e));
        }
        
        return retTime;
    }
    
    /*
     * 获取两个间隔日期间的天数
     */
    public static int getDayBetween(String timeBefore, String timeAfter)
    {
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
        long num = 0;
        
        try
        {
            long diff = sd.parse(timeAfter).getTime() - sd.parse(timeBefore).getTime();
            num = diff / (1000 * 24 * 60 * 60);
        }
        catch (ParseException e)
        {
            logger.error(ExceptionUtils.getStackFrames(e));
        }
        
        return (int)num;
    }
    
    /*
     * 获取一个月最后一天
     */
    public static String getMaxDateOfMonth(String time, String format)
    {
        SimpleDateFormat sd = new SimpleDateFormat(format);
        Calendar cDay = Calendar.getInstance(); 

        try
        {
            Date date = sd.parse(time);
            cDay.setTime(date);
        }
        catch (ParseException e)
        {
            logger.error(ExceptionUtils.getStackFrames(e));
        }
        
        return String.valueOf(cDay.getActualMaximum(Calendar.DAY_OF_MONTH));  
    }
    
    /*
     * Date转String
     */
    public static String dateToString(Date date, String format)
    {
        if (date == null)
        {
            date = new Date();
        }
        
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String retTime = formatter.format(date);
        
        return retTime;
    }
    
    /*
     * 格式化取时间
     */
    public static String formater(String dateString, String format)
    {
        Date date = stringToDate(dateString);
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String retTime = formatter.format(date);
        
        return retTime;
    }

    /*
     * 格式化取时间
     */
    public static String formater(String dateString, String oldFormat, String newFormat)
    {
        Date date = stringToDate(dateString, oldFormat);
        SimpleDateFormat formatter = new SimpleDateFormat(newFormat);
        String retTime = formatter.format(date);
        
        return retTime;
    }

    /*
     * 时间转换
     */
    public static String formater(int dateKey, int timeKey, String format)
    {
        int year = dateKey / 10000;
        int month = (dateKey / 100) % 100;
        int day = dateKey % 100;
        int hour = timeKey / 10000;
        int min = (timeKey / 100) % 100;
        int second = timeKey % 100;
        
        GregorianCalendar calender = new GregorianCalendar(year, month - 1, day, hour, min, second);
        return dateToString(calender.getTime(), format);
    }
    
    /*
     * Date转String
     */
    public static String dateToString(Date date)
    {
        return dateToString(date, "yyyy-MM-dd HH:mm:ss");
    }
    
    /*
     * String转Date
     */
    public static Date stringToDate(String dateString)
    {
        return stringToCalendar(dateString).getTime();
    }
    
    /*
     * String转Date
     */
    public static Date stringToDate(String dateString, String format)
    {
    	SimpleDateFormat sdf = new SimpleDateFormat(format);
    	Date date = null;
    	try{
    		date = sdf.parse(dateString);
    	}catch (Exception e) 
    	{
		}
    	return date;
    }
    
    /*
     * String转Calendar
     */
	public static Calendar stringToCalendar(String dateString)
	{
		if ((dateString == null) || (dateString.length() < 14))
		{
			throw new IllegalArgumentException(dateString);
		}

		String year = dateString.substring(0, 4);
		String month = dateString.substring(4, 6);
		String day = dateString.substring(6, 8);
		String hour = dateString.substring(8, 10);
		String minute = dateString.substring(10, 12);
		String seconds = dateString.substring(12, 14);

		GregorianCalendar calender = new GregorianCalendar(
				Integer.parseInt(year), Integer.parseInt(month) - 1,
				Integer.parseInt(day), Integer.parseInt(hour),
				Integer.parseInt(minute), Integer.parseInt(seconds));

		return calender;
	}
	
    /*
     * 获取当前时间
     */
    public static String getCurrentTime()
    {
      return dateToString(new Date(), "yyyyMMddHHmmss");
    }
    
    /*
     * 获取两个时间之间的间隔（毫秒）
     */
    public static long getTimeBetween(Date d1, Date d2)
    {
        return Math.abs(d2.getTime() - d1.getTime()); 
    }
    
    /*
     * 获取两个时间之间的间隔（分钟）
     */
    public static long getTimeBetween(long d1, long d2)
    {
        long t1 = d1 % 10000;
        long t2 = d2 % 10000;
        
        return Math.abs(t1 % 100 - t2 % 100 + 60 * (t1 / 100 - t2 / 100)); 
    }
    
    /*
     * 获取当前日期
     */
    @SuppressWarnings("deprecation")
	public static String getDateKey(Date date)
    {
		String year = String.format("%04d", date.getYear() + 1900);
		String month = String.format("%02d", date.getMonth() + 1);
		String day = String.format("%02d", date.getDate());
		
		return new StringBuilder().append(year).append(month).append(day).toString();
    }
    
    /*
     * 获取当前时间
     */
    @SuppressWarnings("deprecation")
	public static String getTimeKey(Date date)
    {
		String hour = String.format("%02d", date.getHours());
		String minute = String.format("%02d", date.getMinutes());
		
		return new StringBuilder().append(hour).append(minute).toString();
    }
    
	/*
	 * 当前日期
	 */
	public static String dateNow(String format)
	{
		SimpleDateFormat sdFormat = new SimpleDateFormat(format);
		return sdFormat.format(new Date());
	}
}
